package com.example.demo.commen.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static com.example.demo.commen.Constant.SESSION_USERINFO_KEY;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * user:likai
 * Date:2023-02-18
 * Time:19:05
 */
@Component
public class LoginIntercetor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //通过request的sessionID得到session，如果不存在这个ID就会直接得到一个空值，
        HttpSession session=request.getSession(false);
        //得到sessionID之后，在判断session中是否存值了
        if(session!=null&&session.getAttribute(SESSION_USERINFO_KEY)!=null){
            return true;
        }
        response.setStatus(401);
        return false;
    }
}
